package com.apci.ipreda.security.dao;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.util.CollectionUtils;

import com.apci.ipreda.dao.TipoDataBaseDAO;
import com.apci.ipreda.domain.TipoEntidad;
import com.apci.ipreda.security.domain.Usuario;
import com.apci.ipreda.security.domain.UsuarioRol;

public class AuthenticationDAOImpl implements UserDetailsService {
	
	private final Log logger = LogFactory.getLog(getClass());
	private UsuarioDAO usuarioDAO;
	private TipoDataBaseDAO tipoDataBaseDAO;
	public void setTipoDataBaseDAO(TipoDataBaseDAO tipoDataBaseDAO) {
		this.tipoDataBaseDAO = tipoDataBaseDAO;
	}
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {
		// TODO Auto-generated method stub
		logger.info("loadUserbyUsername->"+userName);
		
		Usuario applicationUser = usuarioDAO.findUserByUserName(userName);
		User user=null;
		if(applicationUser!=null){
			GrantedAuthority[] authorities = null;
			if (!CollectionUtils.isEmpty(applicationUser.getRolList())) {
				int index = -1;
				authorities = new GrantedAuthorityImpl[applicationUser.getRolList().size()];
				for (UsuarioRol userRole : applicationUser.getRolList()) {
					index ++;
					logger.info("add="+userRole.getAuthority());
					authorities[index] = new GrantedAuthorityImpl(userRole.getAuthority());
				}
			}
			logger.info("Authenticar:"+userName);
		
			user = new User(applicationUser.getUserName(),applicationUser.getPassword(), true, true, true, true, authorities);
		} 
		return user;
	}
	public UsuarioDAO getUsuarioDAO() {
		return usuarioDAO;
	}
	public void setUsuarioDAO(UsuarioDAO usuarioDAO) {
		this.usuarioDAO = usuarioDAO;
	}

}
